# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models
from users.models import Person, CompanyInfo, Registry, AuthUser
from utils.models import BaseModel
# from maintenance.models import Task


# 电梯信息表
class ElevatorInfo(BaseModel):
    # link_account = models.CharField(max_length=256, verbose_name=u"对接账号", blank=True, null=True)
    # link_token = models.CharField(max_length=256, verbose_name=u"对接令牌", blank=True, null=True)
    elevator_name = models.CharField(max_length=256, verbose_name=u"电梯简称", null=True, blank=True)
    elevator_no = models.CharField(max_length=50, verbose_name=u"电梯工号", null=True, blank=True, db_index=True)
    internal_no = models.CharField(max_length=50, verbose_name=u"内部编号", null=True, blank=True, db_index=True)
    register_code = models.CharField(max_length=50, verbose_name=u"注册代码", null=True, blank=True, db_index=True)
    factory_no = models.CharField(max_length=50, verbose_name=u"电梯出厂编号", null=True, blank=True, db_index=True)
    elevator_model = models.CharField(max_length=50, verbose_name=u"电梯型号", null=True, blank=True)
    installation_company = models.CharField(max_length=256, verbose_name=u"安装单位", null=True, blank=True)
    manufacturer_company = models.ForeignKey('manufacturer.Manufacturer', verbose_name=u"制造单位", null=True, blank=True, db_index=True)
    maintain_company = models.ForeignKey(CompanyInfo, verbose_name=u"维保单位", null=True, blank=True,
                                         on_delete=models.SET_NULL, related_name="maintain_company_elevator_info", db_index=True)
    property_company = models.ForeignKey(CompanyInfo, verbose_name=u"使用单位", null=True, blank=True,
                                         on_delete=models.SET_NULL, related_name="property_company_elevator_info", db_index=True)
    maintain_company_name = models.CharField(max_length=256, verbose_name=u"维保单位名称", null=True, blank=True)
    property_company_name = models.CharField(max_length=256, verbose_name=u"使用单位名称", null=True, blank=True)
    manufacturer_company_name = models.CharField(max_length=40, verbose_name=u"制造单位名称", null=True, blank=True)
    rated_load = models.CharField(max_length=10, verbose_name=u"额定载重", null=True, blank=True)
    REGISTRY_1 = 10
    REGISTRY_2 = 20
    REGISTRY_3 = 30
    REGISTRY = (
        (10, u'未备案'),
        (20, u'备案成功'),
        (30, u'备案失败'),
    )
    registry_status = models.IntegerField(choices=REGISTRY, default=REGISTRY_1, verbose_name=u'备案状态', db_index=True)
    registry_time = models.DateTimeField(verbose_name=u'备案完成时间', null=True, blank=True, db_index=True)
    BIND_1 = 10
    BIND_2 = 20
    BIND_3 = 30
    BIND = (
        (10, u'未备案'),
        (20, u'备案成功'),
        (30, u'备案失败'),
    )
    is_binded = models.IntegerField(choices=BIND, default=BIND_1, verbose_name=u'电梯人员备案状态', db_index=True)
    ELEVATOR_1 = 10
    ELEVATOR_2 = 20
    ELEVATOR_3 = 30
    ELEVATOR_4 = 40
    ELEVATOR = (
        (10, u"曳引与强制驱动电梯"),
        (20, u"液压驱动电梯"),
        (30, u"杂物电梯"),
        (40, u"自动扶梯"),
    )
    elevator_type = models.IntegerField(choices=ELEVATOR, default=ELEVATOR_1, verbose_name=u"电梯类型", db_index=True)
    U_S_1 = 10
    U_S_2 = 20
    U_S_3 = 30
    U_S_4 = 40
    U_S_5 = 50
    U_S_6 = 60
    U_S_7 = 70
    USAGE_STATUS = (
        (10, u"正常"),
        (20, u"正常,临时停用"),
        (30, u"正常,长期停用"),
        (40, u"正常,拆除"),
        (50, u"维修停用"),
        (60, u"已报停用"),
        (70, u"拆除")
    )
    usage_status = models.IntegerField(default=U_S_1, choices=USAGE_STATUS, verbose_name=u"使用状态", db_index=True)

    stations = models.CharField(max_length=128, verbose_name=u"层 站 门", null=True, blank=True, db_index=True)
    rated_speed = models.CharField(max_length=20, verbose_name=u"额定速度", null=True, blank=True, db_index=True)
    product_company = models.CharField(max_length=50, verbose_name=u"制造厂商", null=True, blank=True, db_index=True)

    DP_1 = 10
    DP_2 = 20
    DP_3 = 30
    DP_4 = 40
    DEV_PROPERTY = (
        (DP_1, u"安置房小区"),
        (DP_2, u"商品房小区"),
        (DP_3, u"医院、学校、机关事业单位"),
        (DP_4, u"其他"),
    )
    elevator_property = models.IntegerField(choices=DEV_PROPERTY, default=DP_1)
    contract = models.ForeignKey('maintenance.Contract', verbose_name=u"维保合同", null=True, blank=True,
                                 on_delete=models.SET_NULL, related_name="elevator_contract_info", db_index=True)
    qr_code = models.CharField(max_length=256, verbose_name=u"电梯二维码", null=True, blank=True)
    elevator_cycle = models.IntegerField(verbose_name=u'电梯维保周期', default=15)
    installation_place = models.CharField(max_length=256, verbose_name=u"安装地点", null=True, blank=True)
    next_yearly_inspection_date = models.DateField(verbose_name=u"下次检验日期", null=True, blank=True)
    inspection_conclusion = models.CharField(verbose_name=u"检验结论", max_length=200, null=True, blank=True)
    inspection_people = models.CharField(verbose_name=u"检验人员", max_length=200, null=True, blank=True)
    inspection_company = models.CharField(verbose_name=u"检验单位", max_length=200, null=True, blank=True)
    iot_realized = models.BooleanField(verbose_name=u"是否安装物联网采集器", default=False)
    num = models.CharField(max_length=10, verbose_name=u"96333编号", null=True, blank=True)
    # address = models.CharField(max_length=200, verbose_name=u"安装位置", null=True, blank=True)
    supervised = models.SmallIntegerField(verbose_name=u"被监管单位监管", default=0)
    address = models.CharField(max_length=200, verbose_name=u"安装位置", null=True, blank=True)
    lng = models.CharField(max_length=50, verbose_name=u"经度", null=True, blank=True)
    lat = models.CharField(max_length=50, verbose_name=u"纬度", null=True, blank=True)
    phone_num = models.CharField(max_length=20, verbose_name=u"电话", null=True, blank=True, default="")

    class Meta:
        verbose_name = u"电梯信息"
        verbose_name_plural = verbose_name

    # def get_task_elevator(self):
    #     task_qs = Task.objects.filter_active(elevator=self)
    #     elevator_ids = []
    #     if task_qs.count():
    #         for task_obj in task_qs:
    #             elevator_ids.append(task_obj.elevator.id)
    #         return elevator_ids
    #     else:
    #         return []

    def registered(self):
        rs = self.register_record()
        r = rs.first()
        if r and r.status:
            return True
        else:
            return False

    def register_record(self):
        rs = Registry.objects.filter(type_for_reg='ElevatorInfo',
                                     reg_obj_id=self.id).order_by('-end_time')
        return rs

    def related_person(self):
        wb = ElevatorPersonInfo.objects.filter(elevator=self, worker_type=ElevatorPersonInfo.WT_1)
        jy = ElevatorPersonInfo.objects.filter(elevator=self, worker_type=ElevatorPersonInfo.WT_2)
        jx = ElevatorPersonInfo.objects.filter(elevator=self, worker_type=ElevatorPersonInfo.WT_3)
        valid = False
        if wb.count() >= 2 and jy.count() >= 2 and jx.count() == 1:
            valid = True
        return [wb, jy, jx], valid

    def __unicode__(self):
        return self.register_code

    def persons(self):
        wb = ElevatorPersonInfo.objects.filter(elevator=self, worker_type=ElevatorPersonInfo.WT_1)
        wb_name = ";".join([w.worker.auth_user.real_name for w in wb])
        jy = ElevatorPersonInfo.objects.filter(elevator=self, worker_type=ElevatorPersonInfo.WT_2)
        jy_name = ";".join([w.worker.auth_user.real_name for w in jy])
        jx = ElevatorPersonInfo.objects.filter(elevator=self, worker_type=ElevatorPersonInfo.WT_3)
        jx_name = ";".join([w.worker.auth_user.real_name for w in jx])
        return [wb_name, jy_name, jx_name]

    def last_checkup_time(self):
        echh = ElevatorCheckUpHistory.objects.filter_active(elevator=self).last()
        return str(echh.create_time) if echh else None

    def last_checkup_score(self):
        echh = ElevatorCheckUpHistory.objects.filter_active(elevator=self).last()
        return echh.score if echh else None

    def next_time(self):
        return self.next_yearly_inspection_date.strftime("%Y-%m-%d") if self.next_yearly_inspection_date else ""

    def follows(self):
        return ElevatorFollowedByUser.objects.filter_active(elevator=self).values_list("user_id", flat=True).distinct()


class ElevatorCheckUpHistory(BaseModel):
    elevator = models.ForeignKey(ElevatorInfo, verbose_name=u"电梯", null=True, blank=True, db_index=True)
    score = models.DecimalField(max_digits=4, decimal_places=1, default=0, verbose_name=u"体检分数")


class ElevatorFollowedByUser(BaseModel):
    """ 电梯关注 """
    user = models.ForeignKey(AuthUser, null=True, blank=True)
    elevator = models.ForeignKey(ElevatorInfo, verbose_name=u"电梯", null=True, blank=True, db_index=True)


class ElevatorPersonInfo(models.Model):
    """
    电梯人员绑定信息表
    """
    WT_1 = 10
    WT_2 = 20
    WT_3 = 30
    WORKER_TYPE = (
        (WT_1, u"维保人员"),
        (WT_2, u"救援人员"),
        (WT_3, u"急修人员"),
    )
    elevator = models.ForeignKey(ElevatorInfo, verbose_name=u"电梯", null=True, blank=True,
                                 on_delete=models.SET_NULL, related_name="elevator_info", db_index=True)
    worker = models.ForeignKey(Person, verbose_name=u"电梯维护人员", null=True, blank=True,
                               on_delete=models.SET_NULL, related_name="maintain_person", db_index=True)
    worker_type = models.IntegerField(choices=WORKER_TYPE, default=WT_1, db_index=True)
    service_id = models.IntegerField(verbose_name=u'服务id', default=0, db_index=True)
    R_S_1 = 10
    R_S_2 = 20
    R_S_3 = 30
    R_S = (
        (R_S_1, u"未绑定"),
        (R_S_2, u"已绑定"),
        (R_S_3, u"绑定失败")
    )
    register_status = models.IntegerField(verbose_name=u"人员电梯绑定备案状态", choices=R_S, default=R_S_1, db_index=True)

    S_1 = 10
    S_2 = 20
    S = (
        (S_1, u'绑定'),
        (S_2, u'解绑'),
    )
    status = models.IntegerField(verbose_name=u"绑定状态", choices=S, default=S_1, db_index=True)
    is_new = models.BooleanField(verbose_name=u'是否为新增加的人员', default=False, db_index=True)


class ElevatorStatistics(BaseModel):
    company = models.ForeignKey(CompanyInfo, verbose_name=u"维保单位", null=True, blank=True,
                                on_delete=models.SET_NULL, related_name="company_elevator", db_index=True)
    numbers = models.IntegerField(verbose_name=u"电梯数量", null=True, blank=True, default=0, db_index=True)
    day = models.DateField(verbose_name=u"日期", auto_now_add=True, db_index=True)


class ThirdElevators(BaseModel):
    register_code = models.CharField(max_length=50, verbose_name=u"注册代码", null=True, blank=True, db_index=True)
    REGISTRY_1 = 10
    REGISTRY_2 = 20
    REGISTRY_3 = 30
    REGISTRY = (
        (10, u'未备案'),
        (20, u'备案成功'),
        (30, u'备案失败'),
    )
    registry_status = models.IntegerField(choices=REGISTRY, default=REGISTRY_1, verbose_name=u'备案状态', db_index=True)


class ElevatorFittings(BaseModel):
    elevator = models.ForeignKey(ElevatorInfo, verbose_name=u"电梯", null=True, blank=True, db_index=True)
    register_code = models.CharField(max_length=50, verbose_name=u"注册代码", null=True, blank=True, db_index=True)
    number = models.CharField(max_length=50, verbose_name=u"配件号", null=True, blank=True)
    old_number = models.CharField(max_length=50, verbose_name=u"原配件号", null=True, blank=True)
    name = models.CharField(max_length=50, verbose_name=u"配件名称", null=True, blank=True)
    person = models.ForeignKey(Person, verbose_name=u"更换人", null=True, blank=True)
    replace_time = models.DateField(verbose_name=u"更换时间", null=True, blank=True)
    warranty_time = models.DateField(verbose_name=u"质保期限", null=True, blank=True)
    register_files = models.CharField(max_length=1024, verbose_name=u"审批文件", null=True, blank=True)
    atype = models.CharField(max_length=50, verbose_name=u"配件类型", null=True, blank=True)
    replace_mode = models.CharField(max_length=20, verbose_name=u"更换方式", null=True, blank=True)

    def person_name(self):
        try:
            return self.person.auth_user.username
        except:
            return ""


class ElevatorYearStatistics(BaseModel):
    year = models.CharField(max_length=20, verbose_name=u"年份", db_index=True, default="")
    number = models.IntegerField(verbose_name=u"电梯数量", null=True, blank=True)
    service_id = models.IntegerField(verbose_name=u"对应的单位", default=0)


























